import Https from "@/utils/Https";
import { CloseCircleFilled, PlusOutlined } from "@ant-design/icons";
import { ProTable, TableDropdown } from "@ant-design/pro-components";
import { Button, message, Modal, Space, Spin } from "antd";
import { FC, useEffect, useRef, useState } from "react";
import { calcColumnsTwo } from "../configFile";
import { history } from "umi";
import OrderModal from "../orderModal";
import { setItem } from "@/utils/localstorage";
const BrandVenue: FC<any> = (props) => {
  const { regionList, onSuccess } = props;
  const actionRef = useRef();
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [modal, contextHolder] = Modal.useModal();
  const [qrcode, setQrcode] = useState(false);
  const [QRCodeUrl, setQRCodeUrl] = useState("");
  const [venueObj, setVenueObj] = useState({});
  const [qrError, setQrError] = useState("");
  const [venueNum, setVenueNum] = useState({
    canBeCreateVenueNum: 0,
    hasBeenCreateVenueNum: 0,
  });
  //获取当前创建场馆列表
  const getVenueNum = async () => {
    let res = await Https.get("/venue/info/tenantVenueNum", {}, true);
    if (res.code == 200) {
      setVenueNum(res.data);
    } else {
      setVenueNum({ canBeCreateVenueNum: 0, hasBeenCreateVenueNum: 0 });
    }
  };
  //获取场馆列表
  const getList = async (params) => {
    let records = [];
    let total = 0;
    setLoading(true);
    let res: any = await Https.post(
      "/venue/info/venueList",
      { ...params, region: params.cascader },
      true
    );
    if (res.code == 200) {
      records = res.data.records;
      total = res.data.total;
    } else {
      message.error(res.msg);
    }
    setLoading(false);
    return { success: true, data: records, total };
  };
  //进入场馆
  const goVenueDetails = async (item) => {
    let res = await Https.get("/venue/info/validatedPeriod", {}, true);
    if (res.code == 200) {
      await Https.get("/venue/info/changeVenue", { id: item.id });
      setItem("venueInfo", item);
      window.location.replace("/welcome");
    } else {
      modal.confirm({
        title: (
          <div>
            <CloseCircleFilled
              style={{
                color: "red",
                fontSize: "18px",
                marginRight: "5px",
              }}
            />
            提示
          </div>
        ),
        icon: null,
        content: "套餐已过期, 请先续费或者升级再进入场馆",
        okText: "管理订单",
        onCancel: () => {},
        onOk: () => {
          onSuccess("2");
        },
      });
    }
  };
  //启用禁用
  const toggleState = async (params) => {
    let res = await Https.post(
      "/venue/info/updateVenueStatus?id=" + params.id,
      {},
      true
    );
    if (res.code == 200) {
      message.success("操作成功");
      actionRef.current && actionRef.current.reload();
    } else {
      message.error(res.msg);
    }
  };
  const changeCanvasToPic = () => {
    const x = new XMLHttpRequest();
    x.open("GET", QRCodeUrl, true);
    x.responseType = "blob";
    x.onload = function () {
      const url = window.URL.createObjectURL(x.response);
      const a = document.createElement("a");
      a.href = url;
      a.download = venueObj.venueName + ".png";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };
    x.send();
  };
  //获取小程序码
  const getQrcodeUlr = async (id) => {
    setLoading(true);
    setQrcode(true);
    setQrError("");
    let res = await Https.get("/venue/info/generateCodeUrl", { id }, true);
    if (res.code == 200) {
      setQRCodeUrl(res.data);
    } else {
      setQrError(res.msg);
      message.error(res.msg);
    }
    setLoading(false);
  };
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operate",
    hideInSearch: true,
    width: 200,
    align: "center",
    render: (_, record) => {
      return (
        <Space>
          <Button
            type="link"
            disabled={record.venueStatus == 1}
            onClick={() => {
              goVenueDetails(record);
            }}
          >
            进入场馆{">>"}
          </Button>
          <TableDropdown
            key="actionGroup"
            menus={[
              {
                key: "edit",
                name: (
                  <a
                    onClick={() => {
                      history.push(
                        `/brand/information/venueDetails/${record.id}`
                      );
                    }}
                  >
                    编辑
                  </a>
                ),
              },
              {
                key: "status",
                name:
                  record.venueStatus == "0" ? (
                    <a
                      style={{ color: "red" }}
                      onClick={() => toggleState({ id: record.id })}
                    >
                      禁用
                    </a>
                  ) : (
                    <a onClick={() => toggleState({ id: record.id })}>启用</a>
                  ),
              },
              {
                key: "code",
                name: (
                  <a
                    onClick={() => {
                      getQrcodeUlr(record.id);
                      setVenueObj(record);
                    }}
                  >
                    小程序码
                  </a>
                ),
              },
            ]}
          />
        </Space>
      );
    },
  };
  useEffect(() => {
    getVenueNum();
  }, []);
  return (
    <div>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            disabled={
              venueNum.hasBeenCreateVenueNum >= venueNum.canBeCreateVenueNum
            }
            onClick={() => {
              history.push("/brand/information/venueDetails/0");
            }}
          >
            新建场馆({venueNum.hasBeenCreateVenueNum}/
            {venueNum.canBeCreateVenueNum})
          </Button>,
          venueNum.hasBeenCreateVenueNum >= venueNum.canBeCreateVenueNum && (
            <a
              style={{ marginLeft: "5px" }}
              onClick={() => {
                setOpen(true);
              }}
            >
              可创建场馆满额,去加购{">>"}
            </a>
          ),
        ]}
        request={async (params) => {
          return await getList(params);
        }}
        scroll={{ x: 1500 }}
        loading={loading}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumnsTwo({ operate, regionList })}
      />
      <OrderModal
        open={open}
        title={"加购场馆"}
        type={3}
        onClose={() => {
          setOpen(false);
        }}
        activeKey={"1"}
      ></OrderModal>
      <Modal
        open={qrcode}
        title="小程序码"
        onCancel={() => {
          setQrcode(false);
          setQRCodeUrl("");
        }}
        footer={false}
      >
        <Spin spinning={loading}>
          <div style={{ minHeight: "150px" }}>
            {QRCodeUrl && (
              <>
                <div
                  style={{
                    width: "100%",
                    textAlign: "center",
                    marginBottom: "20px",
                  }}
                >
                  <img
                    id="qrCode"
                    style={{ width: "200px", height: "200px" }}
                    src={QRCodeUrl}
                  />
                </div>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    flexDirection: "column",
                  }}
                >
                  <Button
                    style={{
                      marginTop: "20px",
                    }}
                    type="primary"
                    onClick={() => {
                      changeCanvasToPic();
                    }}
                  >
                    保存本地
                  </Button>
                </div>
              </>
            )}
            {qrError && (
              <>
                <div
                  style={{
                    width: "100%",
                    textAlign: "center",
                    marginBottom: "20px",
                  }}
                >
                  {qrError}
                </div>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    flexDirection: "column",
                  }}
                >
                  <Button
                    style={{
                      marginTop: "20px",
                    }}
                    type="primary"
                    onClick={() => {
                      getQrcodeUlr(venueObj.id);
                    }}
                  >
                    重新生成二维码
                  </Button>
                </div>
              </>
            )}
          </div>
        </Spin>
      </Modal>
      {contextHolder}
    </div>
  );
};
export default BrandVenue;
